<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useUserScoreRecordHook } from "./utils/hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Delete from "@iconify-icons/ep/delete";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import View from "@iconify-icons/ep/view";
import { CommonUtils } from "@/utils/common";
import UserScoreRecordFormModal from "@/views/cafuc/dataView/userScoreRecord/userScoreRecord-form-modal.vue";
import UserScoreRecordImportModal from "@/views/cafuc/dataView/userScoreRecord/userScoreRecord-import-modal.vue";
import EditPen from "@iconify-icons/ep/edit-pen";
import { UserScoreRecordPageResponse, calculateAllUserScoreApi } from "@/api/performance/userScoreRecord";
import AddFill from "@iconify-icons/ri/add-circle-line";
import Upload from "@iconify-icons/ep/upload";
import { getAllUsersSimpleApi, type UserSimpleDTO } from "@/api/system/user";
import { getDeptTree } from "@/api/system/dept";
import { ElMessage } from "element-plus";

defineOptions({
  name: "userScoreRecordList"
});

const tableRef = ref();

const searchFormRef = ref();
const {
  searchFormParams,
  pageLoading,
  exportLoading,
  columns,
  dataList,
  pagination,
  timeRange,
  defaultSort,
  multipleSelection,
  onSearch,
  resetForm,
  onSortChanged,
  exportAllExcel,
  getUserScoreRecordList,
  handleDelete,
  handleBulkDelete
} = useUserScoreRecordHook();

// 用户搜索相关
const allUsers = ref<UserSimpleDTO[]>([]);
const userOptions = ref<UserSimpleDTO[]>([]);

async function fetchAllUsersSimple() {
  try {
    const { data } = await getAllUsersSimpleApi();
    allUsers.value = data || [];
    userOptions.value = allUsers.value;
  } catch (e) {
    console.error(e);
  }
}

function remoteSearchUsers(query: string) {
  const q = (query || "").trim();
  if (!q) {
    userOptions.value = allUsers.value;
    return;
  }
  const lower = q.toLowerCase();
  userOptions.value = allUsers.value.filter(u =>
    (u.nickname || "").toLowerCase().includes(lower) ||
    (u.deptName || "").toLowerCase().includes(lower)
  );
}

function getUserLabel(u: UserSimpleDTO) {
  const name = u.nickname || "";
  const dept = u.deptName || "";
  return dept ? `${name}（${dept}）` : name;
}

// 部门树相关
const deptTree = ref([]);

onMounted(async () => {
  // 加载用户列表
  await fetchAllUsersSimple();

  // 加载部门树
  try {
    const { data } = await getDeptTree();
    if (data) {
      // 转换数据格式
      const convertDeptTree = (nodes) => {
        return nodes.map(node => ({
          value: node.id,
          label: node.label,
          children: node.children ? convertDeptTree(node.children) : undefined
        }));
      };
      // 若 data 本身是数组，直接转换
      if (Array.isArray(data)) {
        deptTree.value = convertDeptTree(data);
      } else {
        // 若 data 不是数组，将其包裹成数组再转换
        deptTree.value = convertDeptTree([data]);
      }
    }
  } catch (error) {
    console.error('获取部门树数据失败:', error);
  }
});

const opType = ref<"add" | "update">("add");
const modalVisible = ref(false);
const opRow = ref<UserScoreRecordPageResponse>();
function openDialog(type: "add" | "update", row?: UserScoreRecordPageResponse) {
  opType.value = type;
  opRow.value = row;
  modalVisible.value = true;
}

const importModalVisible = ref(false);
function openImportDialog() {
  importModalVisible.value = true;
}

const router = useRouter();

// 刷新用户分数相关
const refreshLoading = ref(false);

async function handleRefreshUserScore() {
  refreshLoading.value = true;
  try {
    await calculateAllUserScoreApi();
    ElMessage.success("刷新用户分数任务已提交，请稍后查看结果");
    // 可选：刷新列表
    // onSearch(tableRef.value);
  } catch (error: any) {
    console.error("刷新用户分数失败:", error);
    
    // 拦截器现在会 reject 完整的响应对象 { code, msg, data }
    // 也可能 reject 其他类型的错误（如网络错误），需要兼容处理
    let errorResponse = null;
    
    // 如果 error 本身就是响应对象（包含 code, msg, data）
    if (error && typeof error === "object" && "code" in error) {
      errorResponse = error;
    } 
    // 兼容旧格式：error.response.data
    else if (error?.response?.data) {
      errorResponse = error.response.data;
    }
    // 兼容旧格式：error.data
    else if (typeof error === "object" && error?.data && "code" in error.data) {
      errorResponse = error.data;
    }
    
    // 检查是否是频率限制错误（code === 102，数据在 data 字段中）
    if (errorResponse?.code === 102 && errorResponse?.data) {
      const data = errorResponse.data;
      const nextAvailableTime = data.nextAvailableTime;
      const remainingSeconds = data.remainingSeconds;
      
      let message = "请求过于频繁，请稍后再试";
      
      if (nextAvailableTime) {
        try {
          // 解析 ISO 格式时间字符串
          const timeStr = new Date(nextAvailableTime).toLocaleString("zh-CN", {
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit",
            hour12: false
          });
          message = `请求过于频繁，下次可刷新时间：${timeStr}`;
        } catch (e) {
          message = `请求过于频繁，下次可刷新时间：${nextAvailableTime}`;
        }
      } else if (remainingSeconds !== undefined && remainingSeconds !== null) {
        // 如果有剩余秒数，计算并显示具体时间
        const nextTime = new Date(Date.now() + remainingSeconds * 1000);
        try {
          const timeStr = nextTime.toLocaleString("zh-CN", {
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit",
            hour12: false
          });
          message = `请求过于频繁，还需等待 ${remainingSeconds} 秒，下次可刷新时间：${timeStr}`;
        } catch (e) {
          message = `请求过于频繁，还需等待 ${remainingSeconds} 秒`;
        }
      }
      
      // 显示详细的错误信息（拦截器可能已经显示了简单消息，这里显示更详细的信息）
      ElMessage.error(message);
    } else {
      // 其他错误：如果拦截器已经显示了错误消息，这里就不重复显示了
      // 但如果错误消息中没有详细信息，这里可以显示更详细的错误
      const errorMsg = errorResponse?.msg || error?.message || error || "刷新用户分数失败";
      // 只有当错误消息不包含"请求过于频繁"时才显示，避免重复
      if (typeof errorMsg === "string" && !errorMsg.includes("请求过于频繁") && !errorMsg.includes("调用太过频繁")) {
        ElMessage.error(errorMsg);
      }
    }
  } finally {
    refreshLoading.value = false;
  }
}

function viewDetail(row: UserScoreRecordPageResponse) {
  router.push({
    path: "/cafuc/dataView/submission",
    query: {
      owner: row.userId.toString()
    }
  });
}
</script>

<template>
  <div class="main">
    <!-- 搜索栏 -->
    <el-form
      ref="searchFormRef"
      :inline="true"
      :model="searchFormParams"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
    >
      <el-form-item label="用户" prop="userId">
        <el-select
          v-model="searchFormParams.userId"
          filterable
          remote
          reserve-keyword
          placeholder="搜索并选择用户"
          :remote-method="remoteSearchUsers"
          clearable
          class="!w-[200px]"
        >
          <el-option
            v-for="u in userOptions"
            :key="u.userId"
            :label="getUserLabel(u)"
            :value="u.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <el-cascader
          v-model="searchFormParams.deptId"
          :options="deptTree"
          :props="{
            value: 'value',
            label: 'label',
            emitPath: false,
            checkStrictly: true
          }"
          clearable
          placeholder="请选择部门"
          class="!w-[200px]"
        />
      </el-form-item>
      <el-form-item label="考核年度" prop="assessmentYear">
        <el-input
          v-model="searchFormParams.assessmentYear"
          placeholder="请输入考核年度"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="pageLoading"
          @click="onSearch(tableRef)"
        >
          搜索
        </el-button>
        <el-button
          :icon="useRenderIcon(Refresh)"
          @click="resetForm(searchFormRef, tableRef)"
        >
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- table bar 包裹  table -->
    <PureTableBar title="用户分数记录列表" :columns="columns" @refresh="onSearch">
      <!-- 表格操作栏 -->
      <template #buttons>
        <!-- <el-button
          type="primary"
          :icon="useRenderIcon(AddFill)"
          @click="openDialog('add')"
        >
          新增用户分数记录
        </el-button>
        <el-button
          type="primary"
          :icon="useRenderIcon(Upload)"
          @click="openImportDialog"
        >
          导入数据
        </el-button> -->
        <!-- <el-button
          type="danger"
          :icon="useRenderIcon(Delete)"
          @click="handleBulkDelete(tableRef)"
        >
          批量删除
        </el-button> -->
        <!-- <el-button
          type="primary"
          @click="CommonUtils.exportExcel(columns, dataList, '用户分数记录列表')"
        >单页导出</el-button
        > -->
        <el-button
          type="primary"
          :icon="useRenderIcon(Refresh)"
          :loading="refreshLoading"
          @click="handleRefreshUserScore"
        >
          刷新用户分数
        </el-button>
        <el-button 
          type="primary" 
          :loading="exportLoading"
          @click="exportAllExcel"
        >
          全部导出
        </el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          border
          ref="tableRef"
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="pageLoading"
          :size="size"
          adaptive
          :data="dataList"
          :columns="dynamicColumns"
          :default-sort="defaultSort"
          :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="getUserScoreRecordList"
          @page-current-change="getUserScoreRecordList"
          @sort-change="onSortChanged"
          @selection-change="
            rows => (multipleSelection = rows.map(item => item.id))
          "
        >
          <template #operation="{ row }">
            <!-- <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(EditPen)"
              @click="openDialog('update', row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              :title="`是否确认删除编号为${row.id}的这条用户分数记录`"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="danger"
                  :size="size"
                  :icon="useRenderIcon(Delete)"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm> -->
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(View)"
              @click="viewDetail(row)"
            >
              查看详情
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <user-score-record-form-modal
      v-model="modalVisible"
      :type="opType"
      :row="opRow"
      @success="onSearch"
    />
    <user-score-record-import-modal
      v-model="importModalVisible"
      @success="onSearch"
    />
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>

